package br.com.felix.fwt.ui;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

import br.com.felix.fwt.log.LoggerFactory;
import br.com.felix.fwt.ui.exception.ComponentRenderException;

/**
 * The Class Button implements the HTML input of the type button or image.
 * If you define the image property, than it will be of the type image.
 * Button otherwise.
 * <p>
 * This is currently the only class that implements behavior for the action listener.
 * If the actionListener is not null, this class will evoke a form submit on the click event.
 * </p>
 */
public class Button extends BaseComponent implements Disable{

	private static final long serialVersionUID = -4009374434389383949L;

	private static Logger logger = LoggerFactory.getLogger(Button.class);
	
	/** The image. */
	public Image image;
	
	private boolean disabled = false;

	{
	    this.cssClass = "fwtbutton";
	}
	
	/**
     * Instantiates a new button.
     * 
     * @param value the button's value (text).
     */
    public Button(String value){
        super(value);
    }
	
	/* (non-Javadoc)
	 * @see br.com.felix.fwt.ui.BaseComponent#write(java.io.PrintWriter)
	 */
	@Override
	public void write(PrintWriter out) throws ComponentRenderException {
		if(!authorized()) return;
		String type = (image==null?"button":"image");
		out.write("\n<input class=\"");
		out.write(cssClass);
		out.write("\" type=\"");
		out.write(type);
		out.write("\" name=\"");
		out.write(getName());
		out.write("\" value=\"");
		out.write(getValue());
		out.write("\"");
		if(type.equals("image")){
			out.print(" src=\"");
			out.print(image.getValue());
			out.print("\" alt=\"");
			out.print(getValue());
			out.print("\" ");
		}
		if(style!=null){
			out.print(style);
		}
		if(disabled){
			out.print(" disabled=\"");
			out.print(disabled);
			out.print("\" ");
		}
		if(this.actionListener!=null){
			actionListener.write(out);
		}
		else{
			logger.warn("Button without actionListener.");
		}
		out.write("/>");
	}

	
	
	@Override
	public boolean equals(Object obj) {
		if(obj==null)return false;
		if(!(obj instanceof Button))return false;
		Button btn = (Button)obj;
		String name = getName();
		if(btn.getName()==null || name ==null)return false;
		return name.equals(btn.getName());
	}

	
	@Override
	public int hashCode() {
	    String name = getName();
		if(name!=null){
			return name.hashCode();
		}
		return super.hashCode();
	}

	@Override
	public boolean isDisabled() {
		return disabled;
	}

	@Override
	public void setDisabled(boolean disabled) {
		this.disabled = disabled;
	}

	

}
